﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using V2TEK.NET.SH.Silverlight.Charts.TreeGridHelper;
using System.Windows.Controls.Primitives;
using V2TEK.NET.SH.Silverlight.Charts.GanttHelper;
using V2TEK.NET.SH.Silverlight.Charts.Core;
using System.Windows.Data;
using System.ComponentModel;

namespace V2TEK.NET.SH.Silverlight.Charts
{
    /// <summary>
    /// 使用Gantt调用TreeGrid时，Gantt将自动协调其数据源更新
    /// 根据ItemsSource 和 RowHeight生成匹配GanttPanel的Grid
    /// 该控件可独立运行
    /// </summary>
    public class TreeGrid : DataGrid
    {
        private Setter _headerHeightSetter = null;

        public Type EntryLayoutProvider = typeof(SimpleTreeGridLayout);

        public Type ExpanderProvider
        {
            get;
            set;
        }

        public static DependencyProperty ViewPortHeightProperty = DependencyProperty.Register("ViewPortHeight", typeof(double), typeof(TreeGrid), new PropertyMetadata(20d));
        public static DependencyProperty YPositionProperty = DependencyProperty.Register("YPosition", typeof(double), typeof(TreeGrid), new PropertyMetadata(0d, new PropertyChangedCallback(YPositionChangeCallBack)));
        public static DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof(object), typeof(TreeGrid), null);
        public static readonly DependencyProperty ExpandLevelProperty = DependencyProperty.Register("ExpandLevel", typeof(int), typeof(TreeGrid), new PropertyMetadata(1));

        protected static void YPositionChangeCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            //int nv = Convert.ToInt32(args.NewValue);
            //int ov = Convert.ToInt32(args.OldValue);

            //TreeGrid t = obj as TreeGrid;
            //if (t._entryLayout != null)
            //{
            //    if (nv > ov)
            //    {
            //        t.ScrollToRow(nv + (int)(t.ViewPortHeight / t.RowHeight) - 1);
            //    }
            //    else
            //    {
            //        t.ScrollToRow(nv);
            //    }
            //}
        }

        private void ScrollToRow(int rowIndex)
        {
            DataGridColumn col = this.CurrentColumn;
            if (col == null)
                col = this.Columns[0];
            if (col != null)
            {
                int count = this.TreeGridLayout.Items.Count;
                if (rowIndex < count)
                    this.ScrollIntoView(this.TreeGridLayout.Items[rowIndex], col);
                else
                    //确保最后一条目显示
                    this.ScrollIntoView(this.TreeGridLayout.Items[count - 1], col);
            }
        }

        public TreeGrid()
        {
            this.LoadingRow += new EventHandler<DataGridRowEventArgs>(TreeGrid_LoadingRow);
            this.TreeGridLayout = Activator.CreateInstance(EntryLayoutProvider) as AbstractTreeGridLayout;
            //this.TreeGridLayout.Rows.CollectionChanged += this.TreeGridLayout.
            this.HierarchicalColumnIndex = 0;
            this.ExpanderProvider = typeof(SimpleTaskExpander);

            this.SelectionMode = DataGridSelectionMode.Single;

        }

        //protected override void OnMouseWheel(MouseWheelEventArgs e)
        //{
        //    base.OnMouseWheel(e);

        //    if (e.Delta > 0)
        //    {
        //        this.SelectedIndex = this.SelectedIndex - 1;
        //        if (this.SelectedIndex < 0)
        //            this.SelectedIndex = -1;
        //    }
        //    else
        //    {
        //        int index = this.SelectedIndex;
        //        this.SelectedIndex = this.SelectedIndex + 1;
        //        if (this.SelectedIndex < 0)
        //            this.SelectedIndex = index;
        //    }
        //    this.ScrollIntoView(this.SelectedItem, this.CurrentColumn);
        //}

        void TreeGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            if (this.Column != null)
            {
                AbstractExpander expander = Column.GetExpander(e.Row);
                expander.ExpandChange -= new ExpandChangeEventHandler(expander_ExpandChange);
                expander.ExpandChange += new ExpandChangeEventHandler(expander_ExpandChange);
            }
        }

        private AbstractTreeGridLayout _entryLayout;
        public AbstractTreeGridLayout TreeGridLayout
        {
            get
            {
                if(_entryLayout == null)
                {
                    this.TreeGridLayout = Activator.CreateInstance(EntryLayoutProvider) as AbstractTreeGridLayout;
                }
                return _entryLayout;
            }
            set
            {
                if (_entryLayout != null)
                    _entryLayout.OnLayoutUpdate -= new LayoutUpdate(this.OnUpdate); 
               
                _entryLayout = value;
                _entryLayout.OnLayoutUpdate += new LayoutUpdate(this.OnUpdate);
            }
        }

        public void OnUpdate(object sender, LayoutUpdateEventArgs args)
        {
            _entryLayout = args.Layout as AbstractTreeGridLayout;
            if (_entryLayout.Items != null && _entryLayout.Items.Count > 0)
            {
                //this.ItemsSource = null;
                this.ItemsSource = _entryLayout.Items;
            }
        }

        private double mHeaderHight = 60;
        public double HeaderHeight
        {
            set
            {
                if (_headerHeightSetter == null)
                {
                    _headerHeightSetter = new Setter(DataGridColumnHeader.HeightProperty, value);
                    if (this.ColumnHeaderStyle == null)
                    {
                        Style style = new Style(typeof(DataGridColumnHeader));
                        style.Setters.Add(_headerHeightSetter);
                        this.ColumnHeaderStyle = style;
                    }
                    else
                    {
                        ColumnHeaderStyle.Setters.Add(_headerHeightSetter);
                    }
                }
                mHeaderHight = value;
            }
            get
            {
                return mHeaderHight;
            }
        }

        public int ExpandLevel
        {
            get
            {
                return (int)GetValue(ExpandLevelProperty);
            }
            set
            {
                SetValue(ExpandLevelProperty, value);
            }
        }

        public object DataSource
        {
            get
            {
                return GetValue(DataSourceProperty);
            }
            set
            {
                SetValue(DataSourceProperty, value);
            }
        }

        public double ViewPortHeight
        {
            get { return (double)GetValue(ViewPortHeightProperty); }
            set { SetValue(ViewPortHeightProperty, value); }
        }

        public double YPosition
        {
            get { return (double)GetValue(YPositionProperty); }
            set { SetValue(YPositionProperty, value); }
        }

        protected DataGridRowsPresenter RowsPresenter { get; private set; }

        public RequestDataMode RequestDataMode
        {
            get;
            set;
        }

        public int HierarchicalColumnIndex
        {
            get;
            set;
        }

        public List<DataGridRow> Rows
        {
            get
            {
                return RowsPresenter.Children.Cast<DataGridRow>().ToList();
            }
        }

        public TreeGridExpanderColumn Column
        {
            get;
            internal set;
        }

        //20101019 by ChenYao
        private ScrollBar mVerticalScrollbar;
        public ScrollBar VerticalScrollbar
        {
            get
            {
                return mVerticalScrollbar;
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            RowsPresenter = (DataGridRowsPresenter)GetTemplateChild("RowsPresenter");
            RowsPresenter.LayoutUpdated += new EventHandler(RowsPresenter_LayoutUpdated);
            Column = this.Columns[HierarchicalColumnIndex] as TreeGridExpanderColumn;
            Column.ExpanderProvider = this.ExpanderProvider;

            //20101019 by ChenYao
            mVerticalScrollbar = (ScrollBar)GetTemplateChild("VerticalScrollbar");

            mVerticalScrollbar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(mVerticalScrollbar_ValueChanged);
            mVerticalScrollbar.SmallChange = RowHeight;
        }

        //20101019 by ChenYao
        void mVerticalScrollbar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (VerticalBarScroll != null)
            {
                VerticalBarScroll(this, e);
            }
        }

        public event RoutedPropertyChangedEventHandler<double> VerticalBarScroll;

        void RowsPresenter_LayoutUpdated(object sender, EventArgs e)
        {
            //20101019 by ChenYao
            //if (YPosition > 0)
            //{
            //    ScrollToRow((int)(YPosition + ViewPortHeight / RowHeight) - 1);
            //}
        }

        protected void RaiseExpandChange(RowExpandEventArgs args)
        {
            if (ExpandChange != null)
                ExpandChange(this, args);
        }

        public event ExpandChangeEventHandler ExpandChange;

        void expander_ExpandChange(object sender, RowExpandEventArgs args)
        {
            RaiseExpandChange(args);
            //this._entryLayout.Update();
        }

        public void Update()
        {
            this.TreeGridLayout.Update();
        }

        /// <summary>
        /// 升级
        /// </summary>
        /// <param name="item"></param>
        public void Upgrade(TaskEntryLayoutItem item)
        {
            
        }

        /// <summary>
        /// 降级
        /// </summary>
        /// <param name="item"></param>
        public void Degrade(TaskEntryLayoutItem item)
        {
        }
    }
}
